<template>
    <j-modal
      width="1200"
      :title="title"
      :visible.sync="editModalVisible"
      :fullscreen.sync="fullscreen"
      :switch-fullscreen="switchFullscreen"
      @cancel="handleCancleDbSync"
      :destroyOnClose="true"
      :bodyStyle="{padding:'0px'}"
    >
    <template slot="footer">
      <div style="text-align:center;">
        <a-button @click="handleCancleDbSync">关闭</a-button>
        <a-button :loading="loading" v-if="type !== 'history' && type !== 'history_his'" type="primary" @click="taskSubmit">确认提交</a-button>
      </div>
    </template>
      <div class="table-page-search-wrapper">
        <a-tabs default-active-key="1" tabPosition="left">
          <a-tab-pane key="1" style="padding-top:20px;">
            <span slot="tab">
              <a-icon type="file-text" />
              单据
            </span>
            <a-collapse :activeKey="[1,2,3]" expand-icon-position="right">
              <template #expandIcon="props">
                <a-icon type="caret-right" :rotate="props.isActive ? 90 : 0" />
              </template>
              <a-collapse-panel key="1" header="申请单据" :showArrow="false" forceRender>
                <!-- 流程表单数据 -->
                <template v-if="isComp">
                  <!-- online表单 -->
                  <online :taskData="taskDataCopy" :type="type"></online>
                </template>
                <template v-else>
                  <!-- 表单设计器 -->
                  <task-kdf style="height:50%;" :taskData="taskDataCopy" :type="type"></task-kdf>
                </template>
              </a-collapse-panel>
              <a-collapse-panel v-if="type !== 'history' && type !== 'history_his' && formList.length" key="2" header="办理人单据" :showArrow="false" forceRender>
                <!-- 办理人单据 -->
                <node-kdf ref="nodeKdf" :taskData="taskDataCopy" v-if="formList.length" style="margin-top:10px;"></node-kdf>
              </a-collapse-panel>
              <a-collapse-panel class="task-approval" v-if="type !== 'history' && type !== 'history_his'" key="3" header="处理意见" forceRender>
                <task-approval-card
                  v-if="type !== 'history'"
                  ref="taskApprovalCard"
                  :taskData="taskDataCopy"
                >
                </task-approval-card>
                <other-card style="margin-top:10px;" ref="otherCard"></other-card>
              </a-collapse-panel>
              <a-collapse-panel key="4" header="流程历史" forceRender>
                <!-- <other-card style="margin-top:10px;" ref="otherCard"></other-card> -->
                <!-- 流程历史跟踪 -->
                <history-process-card key="history-process-card2" :taskData="taskDataCopy"></history-process-card>
              </a-collapse-panel>
            </a-collapse>
            <!-- <div style="text-align:center;margin-top:10px;" v-if="type !== 'history' && type !== 'history_his'">
              <a-button type="primary" @click="taskSubmit">
                确认提交
              </a-button>
            </div> -->
          </a-tab-pane>
          <a-tab-pane key="3">
            <span slot="tab">
              <a-icon type="sliders" />
              流程图
            </span>
            <div style="margin-bottom: 20px; height: 400px;overflow: auto;">
              <img v-if="bpmnSrc"  :src="'data:image/svg+xml;base64,'+bpmnSrc">
            </div>
            <!-- 流程历史跟踪 -->
            <a-card title="流程历史" :bodyStyle="{paddingTop:'0px'}" size="small">
              <history-process-card key="history-process-card1" :taskData="taskDataCopy"></history-process-card>
            </a-card>
          </a-tab-pane>
        </a-tabs>
      </div>
    </j-modal>
</template>
<script>
import bpmnViewer from '@/components/bpmn/bpmnViewer'
// import historyOpinionCard from '../components/historyOpinionCard'
import taskApprovalCard from '../components/taskApprovalCard'
import taskKdf from '../components/taskKdf'
import nodeKdf from '../components/nodeKdf'
import Online from '../components/Online'
import OtherCard from '../components/OtherCard'
import historyProcessCard from '../components/historyProcessCard'
import { getFlowImgByInstanceId, completeTask } from '@/api/task'
import { getFlowByModelId } from '@/api/process'
import { getApprovalRecord } from '@/api/task'
export default {
  name: 'taskModal',
  components: {
    bpmnViewer,
    // historyOpinionCard,
    taskApprovalCard,
    taskKdf,
    OtherCard,
    historyProcessCard,
    nodeKdf,
    Online
  },
  props: {
    type: {
      type: String,
      default: ''
    },
    taskData: {
      type: Object,
      default: () => {}
    },
    title: {
      type: String,
      default: '流程办理'
    }
  },
  computed: {
    formList() {
      if (this.taskDataCopy && this.taskDataCopy.appendForm) {
        return (JSON.parse(this.taskDataCopy.appendForm.formJson)).list
      } else {
        return []
      }
    },
    isComp: function() {
      if (this.taskDataCopy && this.taskDataCopy.actReModelFormData) { // 抄送页面数据单独处理
        if (this.taskDataCopy.actReModelFormData.tableName) {
          return true
        } else {
          return false
        }
      }
      if (this.taskDataCopy && this.taskDataCopy.tableName) {
        return true
      } else {
        return false
      }
    }
  },
  watch: {
    'taskData': {
      handler(newVal) {
        this.taskDataCopy = { ...this.taskData }
      },
      deep: true
    },
    'taskDataCopy': {// 流程数据变化，重新请求流程数据
      handler(newVal) {
        getFlowImgByInstanceId({
          processInstanceId: this.taskDataCopy.processInstanceId
        }).then(res => {
          this.bpmnSrc = res.result
        })
        if (this.taskDataCopy.modelId) {
          this.getFlowXml()
        }
      },
      deep: true
    }

  },
  data() {
    return {
      editModalVisible: false,
      fullscreen: true,
      switchFullscreen: true,
      bpmnSrc: '',
      flowXml: '', // 流程图
      taskDataCopy: {},
      loading: false
    }
  },
  methods: {
    handleCancleDbSync() {
      this.editModalVisible = false
    },
    reset(key) {
      this.approvalData[key] = null
    },
    async taskSubmit() {
      try {
        let data
        if (this.$refs.taskApprovalCard) {
          data = this.$refs.taskApprovalCard.approvalData
        } else {
          data = {
            reason: '同意',
            flag: 0
          }
        }
        let formData, appendFormDataId
        if (this.taskDataCopy.appendForm && this.formList.length && data.flag !== 2) { // 选择驳回是附件表单数据不保存
          formData = this.$refs.nodeKdf && await this.$refs.nodeKdf.getKdfData()
          appendFormDataId = this.$refs.nodeKdf.appendFormDataId
        }
        if (data.flag === 2 && !data.nodeId) {
          this.$message.warning('请选择退回节点')
          return false
        }
        if (data.flag === 2 && !data.reason) {
          this.$message.warning('请填写退回原因')
          return false
        }
        const that = this
        this.$confirm({
          title: '提示',
          content: '确认提交审批吗?',
          onOk() {
            const otherCardData = that.$refs.otherCard.approvalData
            const submitData = Object.assign({}, otherCardData, data, { appendFormDataId: appendFormDataId })
            that.completeTaskSubmit(submitData, formData)
          }
        })
      } catch (err) {
        console.log(err)
      }
    },
    completeTaskSubmit(data, appendFormData) { // 流程审批
      this.loading = true
      completeTask({
        comment: data.reason,
        taskId: this.taskData.id,
        procInstId: this.taskData.processInstanceId,
        formDataId: this.taskData.formDataId,
        usernames: data.ccUserRealNames,
        flag: data.flag,
        appendFormId: this.taskData.appendForm && this.taskData.appendForm.id,
        formData: this.taskData.appendForm && JSON.stringify(appendFormData),
        appendFormDataId: data.appendFormDataId,
        nodeId: data.nodeId,
        files: data.files
      }).then(res => {
        this.loading = false
        if (res.success) {
          this.$message.success('流程办理成功')
          this.editModalVisible = false
          this.$emit('ok')
        } else {
          this.$message.error(res.message)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    getFlowXml() {
      getFlowByModelId({ modelId: this.taskDataCopy.modelId }).then((res) => { // 查询已有流程
        if (res.success) {
          this.bpmnVisible = true
          if (res.result !== '{"id":"canvas","resourceId":"canvas","stencilset":{"namespace":"http://b3mn.org/stencilset/bpmn2.0#"}}') {
            this.flowXml = res.result
          } else {
            this.flowXml = ''
          }
        } else {
          this.$message.warning(res.message)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    preview(code, dataId) { // online表单根据code和数据id查询流程数据
      getApprovalRecord({
        tableId: code,
        dataId: dataId
      }).then(res => {
        if (res.success) {
          if (res.result.records.length === 0) {
            this.$message.warning('未查询到流程数据')
            return false
          }
          this.taskDataCopy = res.result.records[0]
          this.editModalVisible = true
        } else {
          this.$message.error(res.message)
        }
      })
    },
    show(data) {
      this.taskDataCopy = { ...data }
      this.editModalVisible = true
    }
  }
}
</script>
<style>

.table-page-search-wrapper .ant-collapse-content-box{
  padding-top:0px;
}
</style>
